package pl.matt.service.impl;

import java.awt.Image;
import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

import pl.matt.media.utils.ImageUtils;
import pl.matt.model.Frame;
import pl.matt.model.FrameRegion;
import pl.matt.model.FrameRegionType;
import pl.matt.service.ExtractorService;

public abstract class AbstractEyeExtractorService extends AbstractExtractorService implements ExtractorService {

	@SuppressWarnings("unused")
	private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(AbstractEyeExtractorService.class);
	
	private String tmpDir = "/tmp/" + getFrameRegionType();
	
	protected FrameRegion getRegion(Frame frame) {
		return frameRegionDao.findVerifiedByFrameAndFrameRegionType(frame, FrameRegionType.FACE);
	}
	
	@Override
	protected String prepareImage(Frame frame) {
		FrameRegion faceRegion = getRegion(frame);
		if (faceRegion != null) {
			int width = faceRegion.getWidth() / 2;
			int height = faceRegion.getHeight() / 2;
			String dst = tmpDir + File.separator + frame.getNumber();
			try {
				int x = getDX(frame);
				int y = getDY(frame);
				Image frameImage = ImageUtils.readImage(frame.getFilePath()).getAsBufferedImage();
				Image dstImage = ImageUtils.cropImage(frameImage, x, y, width, height);
				ImageUtils.writeImage(dstImage, dst);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return dst;
		}
		return null;		
	}

	@Override
	protected void init() {
		try {
			File dir = new File(tmpDir);
			if (dir.exists()) {				
					FileUtils.deleteDirectory(dir);
			}
			dir.mkdirs();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Override
	protected void clean() {
		try {
			FileUtils.deleteDirectory(new File(tmpDir));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Override
	protected int getDY(Frame frame) {
		FrameRegion faceRegion = getRegion(frame);
		int dy = faceRegion.getY();
		int height = faceRegion.getHeight() / 2;
		return dy + height / 4;
	}

}
